﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace CWCS.Core.Library.ScanManager
{
    /// <summary> 
    /// Author: Wesky 
    /// CreateTime: 2021/11/30 11:07:00 
    /// Description: SR1000 通信核心类 
    /// </summary>
    public class KeyenceReaderService : IKeyenceReaderService
    {
        private object _lock = new object();

        /// <summary>
        /// 触发扫码
        /// </summary>
        /// <param name="clientInfo"></param>
        /// <returns></returns>
        public ReadResultInfo ReadBarcode(ref TcpClientInfo clientInfo, string command = "LON")
        {
            ReadResultInfo result = new ReadResultInfo();
            try
            {

                lock (_lock)
                {
                    Stopwatch stopwatch = new Stopwatch();
                    stopwatch.Start();

                    result = ReadCommand(ref clientInfo, command);
                    stopwatch.Stop();
                    if (!result.IsSucceed)
                    {
                        result.ElapsedMilliseconds = stopwatch.ElapsedMilliseconds;
                        result.ReaderNo = clientInfo.ReaderNo;
                        return result;
                    }
                    result.ElapsedMilliseconds = stopwatch.ElapsedMilliseconds;
                    result.ReaderNo = clientInfo.ReaderNo;
                }
            }
            catch (Exception ex)
            {
                result.IsSucceed = false;
                result.Value = ex.Message;
                result.ReaderNo = clientInfo.ReaderNo;
            }

            return result;
        }



        /// <summary>
        /// 手动关闭扫码器
        /// </summary>
        /// <param name="clientInfo"></param>
        public void CloseReader(TcpClientInfo clientInfo, string command = "LOFF")
        {
            try
            {
                lock (_lock)
                {
                    CloseReader(clientInfo.Client, command);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"********************************** >>> 关闭与扫码器的通信失败:{ex.Message}");
            }
        }


        public ReadResultInfo Connection(ref TcpClientInfo clientInfo)
        {
            ReadResultInfo result = new ReadResultInfo();
            try
            {
                clientInfo.Client?.Close();
                clientInfo.Client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                clientInfo.Client.SendTimeout = clientInfo.SendTimeOut;
                clientInfo.Client.ReceiveTimeout = clientInfo.ReceiveTimeOut;
                clientInfo.Client.Connect(new IPEndPoint(clientInfo.Ip, clientInfo.Port));
                result.IsSucceed = true;

            }
            catch (Exception ex)
            {
                result.IsSucceed = false;
                result.Message = $"与基恩士扫码器建立通信连接失败:{ex.Message}";
                result.ReaderNo = clientInfo.ReaderNo;
            }
            return result;
        }

        private ReadResultInfo ReadCommand(ref TcpClientInfo clientInfo, string command = "LON")
        {
            ReadResultInfo result = new ReadResultInfo();
            int count = clientInfo.Count;
            while (--count >= 0)
            {
                try
                {
                    byte[] bytes = Encoding.ASCII.GetBytes($"{command}\r\n");
                    clientInfo.Client.Send(bytes);
                }
                catch (Exception e)
                {
                    // 新建连接
                    var res = Connection(ref clientInfo);
                    if (!res.IsSucceed)
                    {
                        result.IsSucceed = false;
                        result.Message = $"发送扫码请求失败:{e.Message},并且重试建立连接失败:{res.Message}";
                        result.ReaderNo = clientInfo.ReaderNo;
                    }
                    continue;
                }

                try
                {
                    byte[] receiveBytes = new byte[1024];
                    int recCount = clientInfo.Client.Receive(receiveBytes);
                    if (recCount <= 0)
                    {
                        throw new Exception("没有收到扫码器的返回值");
                    }
                    byte[] receiveData = new byte[recCount];
                    Array.Copy(receiveBytes, receiveData, recCount);
                    result.Value = Encoding.UTF8.GetString(receiveData);
                    result.IsSucceed = true;
                    result.Message = "";
                    return result;
                }
                catch (Exception ee)
                {
                    result.IsSucceed = false;
                    result.Message = $"接收扫码器数据失败:{ee.Message}";
                    continue;
                }
            }
            return result;
        }

        private void CloseReader(Socket client, string command = "LOFF")
        {
            try
            {

                byte[] bytes = Encoding.ASCII.GetBytes($"{command}\r\n");
                client.Send(bytes);
            }
            catch (Exception e)
            {
                Console.WriteLine($"********************************** >>> 关闭与扫码器的通信失败:{e.Message}");
            }
        }

    }
}
